document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("photo_input").addEventListener("change", async function(event) {
        const file = event.target.files[0];
        if(!file){
            return;
        }
        
        try {
            let {filename , message} = await uploadFile(file);
            if(filename){
                document.getElementById("photo").value = filename;
                showPreview(file);
            }
            showMessage(message, "success");
        } catch (error) {
            console.error("上传失败:", error);
            showMessage("上传失败: " + error.message, "error");
        }
    });
});

async function uploadFile(file){
    let formData = new FormData();
    formData.append("file", file);
    let response = await fetch("/files/upload", {
        method: "POST",
        body: formData
    });
    
    if(!response.ok){
        // 尝试获取详细的错误信息
        let errorMessage = "上传失败";
        try {
            let errorData = await response.json();
            errorMessage = errorData.message || errorMessage;
        } catch (e) {
            // 如果无法解析JSON，则使用默认错误消息
            errorMessage += " (HTTP " + response.status + ")";
        }
        throw new Error(errorMessage);
    }
    
    let data = await response.json();
    return data;
}

function showPreview(file){
   const preview = document.getElementById("photo_preview");
   const reader = new FileReader();
   reader.onload = function(e){
    // 清空预览容器
    preview.innerHTML = '';
    // 创建图片元素
    const img = document.createElement("img");
    img.src = e.target.result;
    img.style.maxWidth = "200px";
    img.style.maxHeight = "200px";
    // 添加到预览容器
    preview.appendChild(img);
   }
   // 读取文件内容
   reader.readAsDataURL(file);
}

function showMessage(message, type) {
    // 移除之前的消息
    const existingMessage = document.querySelector(".upload-notification");
    if (existingMessage) {
        existingMessage.remove();
    }
    
    // 创建新的消息元素
    const messageDiv = document.createElement("div");
    messageDiv.className = "upload-notification " + (type === "error" ? "error" : "success");
    messageDiv.textContent = message;
    
    // 添加样式
    messageDiv.style.position = "fixed";
    messageDiv.style.top = "20px";
    messageDiv.style.right = "20px";
    messageDiv.style.padding = "10px 20px";
    messageDiv.style.borderRadius = "4px";
    messageDiv.style.color = "white";
    messageDiv.style.fontWeight = "bold";
    messageDiv.style.zIndex = "1000";
    messageDiv.style.boxShadow = "0 2px 10px rgba(0,0,0,0.2)";
    
    if (type === "error") {
        messageDiv.style.backgroundColor = "#f44336";
    } else {
        messageDiv.style.backgroundColor = "#4CAF50";
    }
    
    document.body.appendChild(messageDiv);
    
    // 3秒后自动移除消息
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.remove();
        }
    }, 3000);
}